﻿using Aop.Api.Domain;
using Aop.Api.Request;
using Aop.Api.Response;
using Vin.Tool.AspNetCore.Options;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.AssertCategory;
using Vin.Tool.Core.BasicTypeCategory;

namespace Vin.Extension.Framework.Alipay.Service;

public class VinAlipayTradeCertificateService : VinAlipayBaseService
{
    private string SiteUrl => VinApp.GetConfig<VinOption>().SiteUrl.IsNullOrWhiteSpace()
        ? throw new System.Exception("请配置Vin:SiteUrl")
        : VinApp.GetConfig<VinOption>().SiteUrl!;

    private string NotifyUrl => AlipayConfig.Notify != null && AlipayConfig.Notify.Trade.IsNotNullOrWhiteSpace()
        ? AlipayConfig.Notify.Trade.IsUrl()
            ? AlipayConfig.Notify.Trade!
            : $"{SiteUrl}{AlipayConfig.Notify.Trade}"
        : string.Empty;

    #region 小程序

    /// <summary>
    /// 统一收单交易创建接口
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<AlipayTradeCreateResponse> Create(AlipayTradeCreateModel model)
    {
        model.OpAppId ??= AlipayConfig.AppId;

        var request = new AlipayTradeCreateRequest();

        if (NotifyUrl.IsNotNullOrWhiteSpace()) request.SetNotifyUrl(NotifyUrl);

        request.SetBizModel(model);

        return await Task.FromResult(SendCertificate(request));
    }

    /// <summary>
    /// 统一收单交易退款接口
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<AlipayTradeRefundResponse> Refund(AlipayTradeRefundModel model)
    {
        var request = new AlipayTradeRefundRequest();

        if (NotifyUrl.IsNotNullOrWhiteSpace()) request.SetNotifyUrl(NotifyUrl);

        request.SetBizModel(model);

        return await Task.FromResult(SendCertificate(request));
    }

    #endregion

    #region APP支付

    /// <summary>
    /// app支付接口2.0(alipay.trade.app.pay)
    /// </summary>
    /// <param name="model"></param>
    /// <returns></returns>
    public async Task<AlipayTradeAppPayResponse> Create(AlipayTradeAppPayModel model)
    {
        var request = new AlipayTradeAppPayRequest();

        if (NotifyUrl.IsNotNullOrWhiteSpace()) request.SetNotifyUrl(NotifyUrl);

        request.SetBizModel(model);

        return await Task.FromResult(SendSdk(request));
    }

    #endregion
}